package com.five.matebook.activity.stat;

import android.annotation.SuppressLint;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Parcelable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.five.matebook.R;
import com.five.matebook.activity.InrecordViewDialog;
import com.five.matebook.activity.db.OneQueryData;
import com.five.matebook.activity.outcome.OutcomeColume;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class IncomeStatFragment extends Fragment {

    private List<OneQueryData> data;
    private Spinner spinnerSortType;

    public IncomeStatFragment() {

    }

    /**
     * @param data 数据列表
     */
    public IncomeStatFragment(List<OneQueryData> data) {
        this.data = data;
    }

    private final Map<String, OneCategoryInfo> mCategoryMaps = new LinkedHashMap<>();
    private List<OneCategoryInfo> mSortedList = new ArrayList<>();
    private final Map<String, OneCategoryInfo> mSubCategoryMaps = new HashMap<>();

    private ListView listView;
    private TextView txtSum;

    private float totalValue;

    private MyAdater adater;

    private static final String KEY_DATA = "data";
    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putParcelableArrayList(KEY_DATA, (ArrayList<? extends Parcelable>) data);
    }

    @SuppressLint("MissingInflatedId")
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            this.data = (List<OneQueryData>) savedInstanceState.get(KEY_DATA);
        }
        View v = inflater.inflate(R.layout.fragment_stat_income, null);
        {
            spinnerSortType = v.findViewById(R.id.spinner_stat_sort_type);
            listView = v.findViewById(R.id.listview);
            txtSum = v.findViewById(R.id.txt_sum);
        }
        sort();
        adater = new MyAdater();
        listView.setAdapter(adater);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                adater.toggleSubCategoryShowState(position);
                adater.notifyDataSetChanged();
            }
        });
        spinnerSortType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                sort();
                adater = new MyAdater();
                listView.setAdapter(adater);
                updateUi();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        updateUi();
        return v;
    }

    private void sort() {
        mCategoryMaps.clear();
        mSubCategoryMaps.clear();
        // sort data here
        String sortColume = null, subSortColume = null;
        switch ((int) spinnerSortType.getSelectedItemId()) {
            case 0:
                // 按用途统计
                sortColume = OutcomeColume.SPENT_USAGE;
                subSortColume = OutcomeColume.SPENT_SENCOND_USAGE;
                break;
            case 1:
                sortColume = OutcomeColume.SPENT_ROLE;
                // 按对象统计
                break;
        }

        // 计算total
        totalValue = 0;
        for (OneQueryData d : data) {
            totalValue += d.getFloat(OutcomeColume.SPENT_MONEY, 0);
        }

        final boolean hasSencondSortValue = !TextUtils.isEmpty(subSortColume);
        // 分类
        for (OneQueryData d : data) {
            String sortValue = d.get(sortColume);
            OneCategoryInfo info = mCategoryMaps.get(sortValue);
            if (info == null) {
                info = new OneCategoryInfo(sortValue);
                mCategoryMaps.put(sortValue, info);
            }

            if (hasSencondSortValue) {
                String secondSortValue = d.get(subSortColume);
                OneCategoryInfo info2 = mSubCategoryMaps.get(secondSortValue);
                if (info2 == null) {
                    info2 = new OneCategoryInfo(secondSortValue);
                    mSubCategoryMaps.put(secondSortValue, info2);
                    info.addSub(info2);
                }
                info2.addSub(d);
            } else {
                info.addSub(d);
            }
        }

        // 计算每个分类的值
        mSortedList = new ArrayList<>(mCategoryMaps.values());
        for (OneCategoryInfo info : mSortedList) {
            info.getTotalValue();

            if (hasSencondSortValue) {
                Collections.sort(info.infos, new Comparator<OneCategoryInfo>() {
                    @Override
                    public int compare(OneCategoryInfo o1, OneCategoryInfo o2) {
                        return (int) (o2.getTotalValue() - o1.getTotalValue());
                    }
                });
            }
        }

        // 排序
        Collections.sort(mSortedList, new Comparator<OneCategoryInfo>() {
            @Override
            public int compare(OneCategoryInfo o1, OneCategoryInfo o2) {
                return (int) (o2.getTotalValue() - o1.getTotalValue());
            }
        });
    }

    private void updateUi() {
        txtSum.setText(String.format("%.2f", totalValue));
        ((MyAdater) listView.getAdapter()).notifyDataSetChanged();
    }

    private class MyAdater extends BaseAdapter {

        class Holder {
            View mRoot;

            public Holder(View root) {
                mRoot = root;
                this.txtCategory = root.findViewById(R.id.txt_main_category);
                this.txtPercent = root.findViewById(R.id.txt_percent);
                this.txtValue = root.findViewById(R.id.txt_value);
                this.progressBar = root.findViewById(R.id.progress_percent);
                this.linearLayoutSubList = root.findViewById(R.id.linear_sub_list);
            }

            void update(final OneCategoryInfo info, boolean viewRecordOnClick) {
                this.txtCategory.setText(info.name);
                this.txtValue.setText(String.format("%.2f", info.getTotalValue()));
                float percent = info.getTotalValue() / totalValue * 100;
                this.txtPercent.setText(String.format("%.2f", percent) + "%");
                if (info.isMaxValueInSameLevel()) {
                    this.txtCategory.setBackgroundColor(Color.parseColor("#3eFF0033"));
                    this.txtValue.setBackgroundColor(Color.parseColor("#3eFF0033"));
                } else {
                    this.txtCategory.setBackgroundColor(Color.TRANSPARENT);
                    this.txtValue.setBackgroundColor(Color.TRANSPARENT);
                }
                this.progressBar.setProgress((int) percent);
                if (viewRecordOnClick) {
                    mRoot.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (info.subs.size() > 0) {
                                new InrecordViewDialog(info.subs).show(getChildFragmentManager(), "dialog");
                            }
                        }
                    });
                } else {
                }
            }

            TextView txtCategory;
            TextView txtPercent;
            TextView txtValue;
            ProgressBar progressBar;
            LinearLayout linearLayoutSubList;
        }

        private final Map<Integer, Boolean> subCategoryState = new HashMap<>();

        synchronized boolean needSubCategory(int position) {
            Boolean ret = subCategoryState.get(position);
            return ret != null ? ret : false;
        }

        synchronized void toggleSubCategoryShowState(int position) {
            subCategoryState.put(position, !needSubCategory(position));
        }

        @Override
        public int getCount() {
            return mCategoryMaps.size();
        }

        @Override
        public Object getItem(int position) {
            return mSortedList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @SuppressLint({"DefaultLocale", "SetTextI18n"})
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = getLayoutInflater().inflate(R.layout.list_stat, null);
                Holder holder = new Holder(convertView);
                convertView.setTag(holder);
            }
            Holder holder = (Holder) convertView.getTag();
            {
                OneCategoryInfo info = (OneCategoryInfo) getItem(position);
                holder.update(info, !info.hasSubCategory());
                if (needSubCategory(position) && info.hasSubCategory()) {
                    holder.linearLayoutSubList.setVisibility(View.VISIBLE);
                    holder.linearLayoutSubList.removeAllViews();
                    for (OneCategoryInfo sub : info.infos) {
                        View temp = getLayoutInflater().inflate(R.layout.list_stat, null);
//                        temp.setBackgroundColor(Color.parseColor("#50CCCCFF"));
                        Holder tempHolder = new Holder(temp);
                        tempHolder.update(sub, true);
                        holder.linearLayoutSubList.addView(temp);
                    }
                } else {
                    holder.linearLayoutSubList.setVisibility(View.GONE);
                }
            }
            return convertView;
        }
    }

    private class OneCategoryInfo {
        String name;
        List<OneQueryData> subs = new ArrayList<>();
        private float totalValue = 0;

        public OneCategoryInfo(String name) {
            this.name = name;
        }

        boolean maxInSameLevel = false;

        public boolean isMaxValueInSameLevel() {
            return maxInSameLevel;
        }

        public boolean hasSubCategory() {
            return this.infos.size() != 0;
        }

        public float getTotalValue() {
            if (totalValue == 0) {
                if (infos.size() != 0) {
                    for (OneCategoryInfo sub : infos) {
                        totalValue += sub.getTotalValue();
                    }
                } else if (subs.size() != 0) {

                }
            }
            return totalValue;
        }

        List<OneCategoryInfo> infos = new ArrayList<>();
        private float maxValue = 0;

        void addSub(OneCategoryInfo categoryInfo) {
            infos.add(categoryInfo);
        }

        void addSub(OneQueryData queryData) {
            subs.add(queryData);
            float value = queryData.getFloat(OutcomeColume.SPENT_MONEY, 0);
            totalValue += value;
        }
    }
}
